package com.uniledger.exchange.base.activity;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;

import com.gyf.barlibrary.ImmersionBar;
import com.orhanobut.logger.Logger;
import com.uniledger.commonlib.iosdialog.AlertDialog;
import com.uniledger.commonlib.util.ToastUtils;
import com.uniledger.exchange.GuideActivity;
import com.uniledger.exchange.HomeActivity;
import com.uniledger.exchange.R;
import com.uniledger.exchange.event.MessageEvent;
import com.uniledger.exchange.home.HomeCenter;
import com.uniledger.exchange.home.scheme.PayFailActivity;
import com.uniledger.exchange.home.scheme.PayQRCodeActivity;
import com.uniledger.exchange.home.scheme.PayResult;
import com.uniledger.exchange.home.scheme.TransferActivity;
import com.uniledger.exchange.model.monitor.NetBroadcastReceiver;
import com.uniledger.exchange.model.monitor.NetUtil;
import com.uniledger.exchange.welcome.WelcomeActivity;
import com.uniledger.languagelib.MultiLanguageUtil;

import org.aviran.cookiebar2.CookieBar;
import org.aviran.cookiebar2.OnActionClickListener;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Method;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Optional;
import butterknife.Unbinder;

public abstract class BaseActivity extends AppCompatActivity implements NetBroadcastReceiver.NetChangeListener {

    protected Unbinder unbinder;
    protected ImmersionBar mImmersionBar;

    @BindView(R.id.wallet_bar)
    protected Toolbar toolbar;

    public static NetBroadcastReceiver.NetChangeListener netChangeListener;
    private NetBroadcastReceiver netBroadcastReceiver;
    /**
     * 网络类型
     */
    protected int netType;
    private AlertDialog netAlertDialog;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //初始化沉浸式
        if (isImmersionBarEnabled())
            initImmersionBar();

        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);

        monitorNet();

        checkNet();
    }

    public void monitorNet() {
        netChangeListener = this;
        //Android 7.0以上需要动态注册
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //实例化IntentFilter对象
            IntentFilter filter = new IntentFilter();
            filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
            netBroadcastReceiver = new NetBroadcastReceiver();
            //注册广播接收
            registerReceiver(netBroadcastReceiver, filter);
        }
    }

    /**
     * 获取传入当前页面的参数
     */
    public abstract void getParams();

    public void initBar() {

        if (!(this instanceof HomeActivity)) {
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        } else {
//            setSupportActionBar(toolbar);
        }
    }

    protected void initImmersionBar() {
        //在BaseActivity里初始化
        mImmersionBar = ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarColor(R.color.colorPrimary);
        if (this instanceof WelcomeActivity) {
            hideBottomUIMenu2();
//            mImmersionBar.navigationBarColor(R.color.colorPrimary);
        } else {
            mImmersionBar.navigationBarColor(R.color.white);
            mImmersionBar.init();
        }

    }

    public void destroyImmersionBar() {
        if (mImmersionBar != null)
            mImmersionBar.destroy();  //在BaseActivity里销毁
    }

    /**
     * 是否可以使用沉浸式
     * Is immersion bar enabled boolean.
     *
     * @return the boolean
     */
    protected boolean isImmersionBarEnabled() {
        return true;
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        unbinder = ButterKnife.bind(this);//绑定View
        getParams();
        initBar();
    }

    /**
     * @param item
     * @return true表示该方法执行完毕后，点击事件不会再向下一个事件处理方法传递了。
     * false表示执行完该方法后，点击事件继续向下传递
     */

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (unbinder != null)
            unbinder.unbind();//解绑View

        destroyImmersionBar();

        hideNetDialog();

        if (netBroadcastReceiver != null) {
            unregisterReceiver(netBroadcastReceiver);
        }

    }

    /**
     * 应用内推送消息订阅
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (this instanceof PayQRCodeActivity) {
            PayResult result = new PayResult(this,HomeCenter.SCHEME_PAYMENT);
            result.errorMessage = event.message;
            PayFailActivity.start(this, result);
        } else {
//            //TODO
//            CookieBar.build(this)
//                    .setTitle(R.string.top_cookie_title)
//                    .setTitleColor(R.color.yellow)
//                    .setMessage(R.string.top_cookie_message)
//                    .setIcon(R.mipmap.ic_launcher_round)
//                    .setDuration(5000)
//                    .setAction("去看看", new OnActionClickListener() {
//                        @Override
//                        public void onClick() {
//
//                        }
//                    })
//                    .show();
        }

    }

    @Override
    public void onStart() {
        super.onStart();
        if (!(this instanceof GuideActivity)) {
            EventBus.getDefault().register(this);
            Logger.d(this.getClass().getName());
        }

    }

    /**
     * 初始化时判断有没有网络
     */
    public boolean checkNet() {
        this.netType = NetUtil.getNetWorkState(BaseActivity.this);
        if (!isNetConnect()) {
            //网络异常，请检查网络
            showNetDialog();
        }
        return isNetConnect();
    }

    /**
     * 判断有无网络 。
     *
     * @return true 有网, false 没有网络.
     */
    protected boolean isNetConnect() {
        if (netType == 1) {
            return true;
        } else if (netType == 0) {
            return true;
        } else if (netType == -1) {
            return false;
        }
        return false;
    }

    @Override
    public void onStop() {
        super.onStop();
        if (!(this instanceof GuideActivity)) {
            EventBus.getDefault().unregister(this);
        }
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu1() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu2() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                    | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE;
            decorView.setSystemUiVisibility(uiOptions);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }

    /**
     * 检查是否存在虚拟按键栏
     *
     * @param context
     * @return
     */
    public boolean hasNavBar(Context context) {
        Resources res = context.getResources();
        int resourceId = res.getIdentifier("config_showNavigationBar", "bool", "android");
        if (resourceId != 0) {
            boolean hasNav = res.getBoolean(resourceId);
            // check override flag
            String sNavBarOverride = getNavBarOverride();
            if ("1".equals(sNavBarOverride)) {
                hasNav = false;
            } else if ("0".equals(sNavBarOverride)) {
                hasNav = true;
            }
            return hasNav;
        } else { // fallback
            return !ViewConfiguration.get(context).hasPermanentMenuKey();
        }
    }

    /**
     * 判断虚拟按键栏是否重写
     *
     * @return
     */
    private String getNavBarOverride() {
        String sNavBarOverride = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                Class c = Class.forName("android.os.SystemProperties");
                Method m = c.getDeclaredMethod("get", String.class);
                m.setAccessible(true);
                sNavBarOverride = (String) m.invoke(null, "qemu.hw.mainkeys");
            } catch (Throwable e) {
            }
        }
        return sNavBarOverride;
    }

    protected void enableDisplayHomeAsHome(boolean active) {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(active);
            actionBar.setHomeAsUpIndicator(R.drawable.ic_home_black_24dp);
        }
    }

    protected void dissableDisplayHomeAsUp() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(false);
        }
    }

    @Override
    public void onChangeListener(int netMobile) {
        this.netType = netMobile;
        if (!isNetConnect()) {
            showNetDialog();
        } else {
            hideNetDialog();
        }
    }

    private void showNetDialog() {
        if (netAlertDialog == null) {
            netAlertDialog = new AlertDialog(BaseActivity.this).builder()
                    .setMsg("Please reconnect if the network is disconnected")
                    .setNegativeButton("Confirm", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
                        }
                    });
        }
        netAlertDialog.show();
    }

    private void hideNetDialog() {
        if (netAlertDialog != null) {
            netAlertDialog.dismiss();
        }
        netAlertDialog = null;
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(MultiLanguageUtil.attachBaseContext(newBase));
    }

}
